<!--
 * @Description: 路侧管理
 * @Author:       zhaixiangjun
 * @Date: 2021-11-02 14:00:49
 * @LastEditors:  zhengxu
 * @LastEditTime: 2021-11-11 17:59:57
-->
<template>
  <BaseOperateTable
    ref="refPage"
    :show-selection="true"
    :header="columns"
    :button-list="{}"
    :query-url="queryUrl"
    :delete-url="deleteUrl"
    :data-filter="tabelDataFilter"
    @operate="tableOperate"
    @query="query"
    @deleted="onRowsDeleted"
    @reset="resetCondition">
    <template v-slot:condition>
      <div>车辆编号：
        <a-input
          v-model:value="condition.vin"
          :allow-clear="true"
          placeholder="请输入车辆编号"/>
      </div>
      <div>路线名称：
        <a-input
          v-model:value="condition.routeName"
          :allow-clear="true"
          placeholder="请输入路线名称"/>
      </div>
      <div>车辆状态：
        <a-select
          v-model:value="condition.onlineStatus"
          :options="CarStatusList"
          :allow-clear="true"
          placeholder="请选择车辆状态"/>
      </div>
      <div>路线方向：
        <a-select
          v-model:value="condition.direction"
          :options="RouteDirectionList"
          :allow-clear="true"
          placeholder="请选择路线方向"/>
      </div>
      <div>创建时间：
        <a-range-picker
          v-model:value="createTimeRange"
          style="width:200px"
          format="YYYY-MM-DD"
          @change="onCreateTimeRangeChange" />
      </div>
    </template>
    <template v-slot:operate>
      <a-button
        type="primary"
        @click="addData">添加关联</a-button>
      <a-button
        type="primary"
        danger
        @click="batchDelete">删除关联</a-button>
    </template>
    <template v-slot:action="{record}">
      <a-button
        type="link"
        @click="tableOperate({eventType:'edit',data: record})">编辑</a-button>
      <a-button
        type="link"
        :disabled="record.onlineStatus === 1"
        @click="tableOperate({eventType:'online',data: record})">上线</a-button>
      <a-button
        type="link"
        :disabled="record.onlineStatus !== 1"
        @click="tableOperate({eventType:'offline',data: record})">下线</a-button>
      <a-button
        type="link"
        danger
        :disabled="record.onlineStatus === 1"
        @click="tableOperate({eventType:'delete',data: record})">删除</a-button>
    </template>
  </BaseOperateTable>
  <BaseFormDialog
    ref="refAddDataDialog"
    :title="dialogTitle"
    :rules="addDataRules"
    :form="addDataForm">
    <template v-slot:vin="{state}">
      <a-select 
        show-search
        v-model:value="state.vin" 
        placeholder="请选择车辆编号"
        :options="vehicleList"/>
    </template>
     <template v-slot:routeId="{state}">
      <a-select 
        show-search
        optionFilterProp="label"
        v-model:value="state.routeId" 
        placeholder="请选择路线名称"
        :options="routeList"/>
    </template>
    </BaseFormDialog>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import { getAllRoutes, addVehicleRouteMap, editVehicleRouteMap, retriveUnMapVehicles, vehicleOnline, vehicleOffline } from '@/api/simulation/carRelevancy'
import { CarStatusList, RouteDirectionList } from '@/config/simulation'
import BaseOperateTable from '@/components/BaseOperateTable.vue'
import BaseFormDialog from '@/components/BaseFormDialog.vue'
import { BasePath } from '@/api/request'

const refPage = ref(null) // 表格实例
const refAddDataDialog = ref(null) // form表单弹窗实例
const dialogTitle = ref('添加信号机') // form表单弹窗标题
/** ========== Table ========== */
const queryUrl = ref(`${BasePath}/vehicleRouteMap/page`) // 分页查询接口URL
const deleteUrl = ref(`${BasePath}/vehicleRouteMap/`) // 批量删除接口URL

/** 表格标题栏配置 */
const columns = ref([
  {
    title: '车辆编号',
    dataIndex: 'vin',
    width: 200,
    ellipsis: true
  },
  {
    title: '路线名称',
    dataIndex: 'routeName',
    width: 200,
    ellipsis: true
  },
  {
    title: '路线方向 ',
    dataIndex: 'directionLabel',
    width: 100,
    ellipsis: true
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 160,
    ellipsis: true
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    width: 160,
    ellipsis: true
  },
  {
    title: '操作人',
    dataIndex: 'updateBy',
    width: 100,
    ellipsis: true
  },
  {
    title: '状态',
    dataIndex: 'onlineStatusLabel',
    width: 100,
    ellipsis: true
  },
  {
    title: '操作',
    dataIndex: 'xxx',
    fixed: "right",
    width: 260,
    slots: { customRender: 'action' }
  }
])

/** 表格数据过滤 */
const tabelDataFilter = (rows) => {
  const result = []
  rows.forEach((item) => {
    let i = { ...item }
    i.onlineStatusLabel = CarStatusList[i.onlineStatus === 1?1:0].label
    i.directionLabel = RouteDirectionList[i.direction || 0].label
    result.push(i)
  })
  return result
}

/** 表格操作列事件 */
const tableOperate = ({ eventType, data }) => {
  if (eventType === 'edit') {
    refAddDataDialog.value.updateFormItem('vin', { disabled: true })
    dialogTitle.value = '编辑关联'
    refAddDataDialog.value.setRequest(editVehicleRouteMap, () => {
      refPage.value.query()
    })
    refAddDataDialog.value.setFormData(data)
    refAddDataDialog.value.show()
  } else if (eventType === 'online') {
    // 车辆上线
    vehicleOnline(data.id).then(() => {
      message.success('车辆上线成功')
      refPage.value.query()
    })
  } else if (eventType === 'offline') {
    // 车辆下线
    vehicleOffline(data.id).then(() => {
      message.success('车辆下线成功')
      refPage.value.query()
    })
  } else {
    // 删除车辆关联关系
    refPage.value.deleteRow(data.id)
  }
}
/** 数据删除成功事件 */
const onRowsDeleted = () =>{
  getVehicleList()
  refPage.value.query()
}
/** ========== Condition ========== */
const createTimeRange = ref([])
// 查询条件
const condition = reactive({
  vin: undefined,
  routeName: undefined,
  onlineStatus: undefined,
  direction: undefined,
  startTime: undefined,
  endTime: undefined
})

/** 重置条件 */
const resetCondition = () => {
  condition.vin = undefined
  condition.routeName = undefined
  condition.onlineStatus = undefined
  condition.direction = undefined
  condition.startTime = undefined
  condition.endTime = undefined
  createTimeRange.value = []
}

/** 点击查询按钮后，进行表格查询 */
const query = () => {
  refPage.value.queryByCondition(condition, true)
}

/** 创建时间改变事件 */
const onCreateTimeRangeChange = (v1, v2) => {
  if (v2.length === 2) {
    let[startTime, endTime] = v2
    condition.startTime = v1.length?(startTime + ' 00:00:00') : undefined
    condition.endTime =  v1.length?(endTime + ' 23:59:59') : undefined
  }
}

/** ========= Operate ========== */
/** 添加数据 */

const addData = () => {
  dialogTitle.value = '添加关联'
  refAddDataDialog.value.updateFormItem('vin', { disabled: false })
  let data = {}
  addDataForm.value.forEach(({ key, value }) => {
    data[key] = value
  })
  refAddDataDialog.value.setRequest(addVehicleRouteMap, () => {
    resetCondition()
    refPage.value.resetQuery()
    getVehicleList();
  })
  refAddDataDialog.value.setFormData(data)
  refAddDataDialog.value.show()
}

/** 批量删除 */
const batchDelete = () => {
  const selectedRows = refPage.value.getSelectedRows()
  const onlineRows =selectedRows.filter(({onlineStatus}) => onlineStatus === 1)
  if(onlineRows.length > 0){
    message.warning('请先下线车辆')
    return
  }
  refPage.value.deleteSelectedRows()
}

/** ========== Form ========== */
const vehicleList = ref([]) // 未与路线关联的车辆列表
const routeList = ref([]) // 路线列表

/** 获取未与路线关联的车辆列表 */
const getVehicleList = () => {
  retriveUnMapVehicles().then(({ data }) => {
    vehicleList.value = (data || []).map((vin) => ({ label: vin, value: vin }))
  })
}
getVehicleList()

/** 获取路线列表 */
const getRouteList = () => {
  getAllRoutes().then(({ data }) => {
    routeList.value = (data || []).map(({ id, name }) => ({ label: name, value: id }))
  })
}
getRouteList()
// 表单的配置
const addDataForm = ref([
  { key: 'vin', value: undefined, label: '车辆编号', custom: true },
  { key: 'routeId', value: undefined, label: '路线名称', custom: true }
])
// 表单校验规则
const addDataRules = reactive({
  vin: [
    { required: true, message: '请选择车辆编号', trigger: 'change' }
  ],
  routeId: [
    { required: true, message: '请选择路线名称', trigger: 'change', type: 'number' }
  ]
})
</script>
<script>
export default {
  name: 'carRelevancy'
}
</script>